package com.leyou.cart.interceptors;

import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//这个拦截器是为了在每个controller运行前,先做一些处理
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    //preHandle是先处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //得到用户id
        String userId = request.getHeader("userId");
        if (StringUtils.isBlank(userId)) {
            log.info("【拦截器获取用户id】异常!请登录！");
            return false;
        }

        log.info("【拦截器获取用户id】id为："+userId);
        //把用户id赋值给UserHolder
        UserHolder.setUserId(Long.valueOf(userId));
        return true;  //true向下执行
    }

    //controller结束后要释放线程中map里的值
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUserId();
    }
}
